<template>
  <div class="login-index">
    <div class="login-bg"></div>
    <div class="login-box">
      <div class="login-form">
        <el-form ref="formRef" :rules="rules" :model="loginForm" label-width="80px" label-position="left">
          <h3>欢迎登录</h3>
          <el-form-item label="账号：" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入账号"/>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password/>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="handleLogin">立即登录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user.js'
import { ElMessage } from "element-plus";

const userStore = useUserStore()
const router = useRouter()
const loginForm = reactive({
  username: 'admin',
  password: 'macro123'
})
const formRef = ref(null)

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '账号不能为空！', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
  ]
})

// 加载状态
const isLoading = ref(false);

// 登录
const handleLogin = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      try {
        await userStore.gotoLogin(loginForm.username, loginForm.password);
        await router.push('/');
      // 登陆之后刷新页面
        window.location.reload();
      } catch (error) {
        console.error('登录时发生错误:', error);
        ElMessage.error('登录失败！！！电磁阀v搞不好你家门口');
      } finally {
        isLoading.value = false;
      }
    } else {
      ElMessage.error('请检查输入项！');
    }
  })
}
</script>

<style scoped lang="scss">
.login-index {
  display: flex;
  width: 100%;
  height: 100%;
  background-color: #f1f1f1;

  .login-bg {
    width: 70%;
    height: 100%;
    border-radius: 0 50px 50px 0;
    background: url('@/assets/login_back.png') no-repeat center center fixed;
    -webkit-background-size: cover;
  }

  .login-box {
    width: 30%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    background-color: #f1f1f1;

    .login-form {
      position: relative;
      width: 100%;
      height: 300px;
      padding: 20px;
      border-radius: 10px;
      background-color: #fff;
      box-shadow: 0 5px 10px #b8d0ff;

      h3 {
        text-align: center;
        font-size: 20px;
        color: #1e1e1e;
        margin-bottom: 20px;
        font-weight: bold;
      }

      .el-form-item {
        margin-bottom: 15px;
        text-align: center;

        .bottom-box {
          width: 100%;
          display: flex;
          justify-content: space-between;
        }
      }

      .el-button {
        width: 100%;
        margin-bottom: 20px;
      }
    }
  }
}
</style>
